#nullable enable
#nullable enable
using Godot;
using System.Collections.Generic;
using System.Linq;

namespace AndroidUnevenRoadGame.Game
{
    /// <summary>
    /// 战斗流程管理：控制敌人生成、回合推进与战斗日志。
    /// </summary>
    public sealed class BattleManager
    {
        private readonly GameRoot _game;

        public int TurnCounter { get; private set; }
        public IReadOnlyList<EnemyState> Enemies => _enemies;
        private readonly List<EnemyState> _enemies = new();
        public readonly List<string> BattleLog = new();

        public BattleManager(GameRoot game)
        {
            _game = game;
        }

        public void StartBattle(List<EnemyDefinition> enemyGroup, MapNodeType nodeType = MapNodeType.Battle)
        {
            _enemies.Clear();
            foreach (var enemy in enemyGroup)
            {
                _enemies.Add(new EnemyState(enemy, _game.CurrentFloor));
            }

            TurnCounter = 1;
            BattleLog.Clear();
            BattleLog.Add("战斗开始");

            _game.Player.StartTurn();
            _game.Player.DrawCards(5);
            _game.ChangeState(GameRoot.GameState.Battle);
            _currentNodeType = nodeType;
        }

        public void PlayCard(string cardId, EnemyState? target = null)
        {
            var card = CardDatabase.Get(cardId);
            if (!_game.Player.Hand.Contains(cardId))
            {
                GD.PushWarning($"手牌中没有卡牌：{cardId}");
                return;
            }

            if (card.Cost > _game.Player.CurrentEnergy)
            {
                GD.PushWarning("能量不足，无法使用该卡牌");
                return;
            }

            _game.Player.SpendEnergy(card.Cost);

            switch (card.Type)
            {
                case CardType.Attack:
                    if (target == null)
                    {
                        GD.PushWarning("攻击卡需要目标");
                        return;
                    }

                    var damage = (int)card.GetParameter("damage", 6);
                    target.TakeDamage(damage);
                    BattleLog.Add($"使用 {card.Name} 对 {target.Definition.Name} 造成 {damage} 点伤害");
                    if (target.IsDead)
                    {
                        BattleLog.Add($"{target.Definition.Name} 被击败");
                        if (HasPlayerWon())
                        {
                            HandleVictory();
                            return;
                        }
                    }
                    break;
                case CardType.Skill:
                    var block = (int)card.GetParameter("block", 5);
                    _game.Player.GainBlock(block);
                    BattleLog.Add($"使用 {card.Name} 获得 {block} 点格挡");

                    var drawCount = (int)card.GetParameter("draw", 0);
                    if (drawCount > 0)
                    {
                        _game.Player.DrawCards(drawCount);
                        BattleLog.Add($"抽到 {drawCount} 张牌");
                    }

                    var energyGain = (int)card.GetParameter("energy", 0);
                    if (energyGain > 0)
                    {
                        _game.Player.GainEnergy(energyGain);
                        BattleLog.Add($"恢复 {energyGain} 点能量");
                    }

                    var discardCount = (int)card.GetParameter("discard", 0);
                    if (discardCount > 0)
                    {
                        _game.Player.DiscardRandom(discardCount);
                        BattleLog.Add($"随机弃置 {discardCount} 张牌");
                    }
                    break;
                case CardType.Power:
                    var powerBlock = (int)card.GetParameter("block", 0);
                    if (powerBlock > 0)
                    {
                        _game.Player.GainBlock(powerBlock);
                        BattleLog.Add($"激活 {card.Name} 即时获得 {powerBlock} 点格挡");
                    }
                    else
                    {
                        BattleLog.Add($"激活能力 {card.Name}");
                    }
                    break;
            }

            _game.Player.Hand.Remove(cardId);
            _game.Player.DiscardPile.Add(cardId);
        }

        public void EndPlayerTurn()
        {
            BattleLog.Add("玩家回合结束");
            _game.Player.DiscardHand();
            foreach (var enemy in _enemies)
            {
                if (enemy.IsDead)
                {
                    continue;
                }

                var damage = enemy.RollAttackDamage();
                _game.Player.TakeDamage(damage);
                BattleLog.Add($"{enemy.Definition.Name} 造成 {damage} 点伤害");
            }

            if (_game.Player.CurrentHp <= 0)
            {
                BattleLog.Add("玩家阵亡");
                _game.ChangeState(GameRoot.GameState.Defeat);
                return;
            }

            if (HasPlayerWon())
            {
                HandleVictory();
                return;
            }

            TurnCounter++;
            _game.Player.StartTurn();
            _game.Player.DrawCards(5);
        }

        private bool HasPlayerWon()
        {
            return _enemies.All(enemy => enemy.IsDead);
        }

        private MapNodeType _currentNodeType = MapNodeType.Battle;

        private void HandleVictory()
        {
            BattleLog.Add("战斗胜利");
            var goldReward = _enemies.Sum(enemy => enemy.Definition.GoldReward);
            if (goldReward > 0)
            {
                BattleLog.Add($"获得 {goldReward} 金币");
                _game.AwardGold(goldReward);
            }

            _game.AdvanceFloor();
            RewardSystem.ShowRewards(_game, _currentNodeType);
        }
    }
}

